import dayjs from 'dayjs'
import classNames from 'classnames'
import { DatePicker, GetProps } from 'antd'
import { CustomCellEditorProps } from '@ag-grid-community/react'

import styles from './styles.module.less'

type TDatePickerProps = GetProps<typeof DatePicker>

interface IDateCellEditorProps extends CustomCellEditorProps<any, string> {
  datePickerProps?: Omit<
    TDatePickerProps,
    'size' | 'defaultValue' | 'value' | 'onChange' | 'picker' | 'open' | 'onOpenChange'
  >
}

export const DateCellEditor = Object.assign(
  ({ api, value, onValueChange, datePickerProps }: IDateCellEditorProps) => {
    let dateValue
    if (typeof value === 'string' && value.trim()) {
      const date = dayjs(value.trim())
      if (date.isValid()) {
        dateValue = date
      }
    }

    return (
      <DatePicker
        allowClear={false}
        {...datePickerProps}
        className={classNames(styles.DateCellEditor, datePickerProps?.className)}
        size="small"
        defaultValue={undefined}
        value={dateValue}
        onChange={(_date, dateString) => {
          onValueChange(typeof dateString === 'string' ? dateString || '' : '')
        }}
        picker="date"
        open
        onOpenChange={open => {
          if (!open) {
            api.stopEditing()
          }
        }}
      />
    )
  },
  {
    /** 用于类型约束 */
    defineProps: (
      props: Pick<IDateCellEditorProps, 'datePickerProps'>,
    ): Pick<IDateCellEditorProps, 'datePickerProps'> => props,
  },
)
